package com.xiaotao.learn.algorithm.list;

import com.xiaotao.learn.algorithm.struct.ListNode;

import java.util.LinkedList;

public class MergeTowList {
    public static void main(String[] args) {
        ListNode.dump(new MergeTowList().mergeTwoLists(
                ListNode.parse(),
                ListNode.parse()
        ));
    }
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode res, last, a;
        if (l1 != null && l2 != null) {
            if (l1.val > l2.val) {
                a = l2;
                l2 = l1;
                l1 =a;
            }
            res = l1;
        } else if (l1 != null) res = l1;
        else if (l2 != null) res = l2;
        else return null;

        last = res;
        while(l1 != null && l2 != null) {
            if(l1.val < l2.val) {
                last = l1;
                l1 = l1.next;
            } else {
                ListNode t = last.next, t2 = l2.next;
                last.next = l2;
                last = l2;
                l2.next = t;
                l2 = t2;
            }
        }
        if(l1 == null && l2 != null && last != l2) {
            last.next = l2;
        }
        return res;
    }
}
